package com.flutter.data_strength;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

public class NetworkUtils {

    Context  context;
    NetworkUtils(Context context){
        this.context = context;
    }
      final String TAG = "NetworkUtils";

      String getNetworkType() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if (connectivityManager != null && telephonyManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                int networkType = networkInfo.getType();

                if (networkType == ConnectivityManager.TYPE_WIFI) {
                    return "Wi-Fi";
                } else if (networkType == ConnectivityManager.TYPE_MOBILE) {
                    int networkSubType = telephonyManager.getNetworkType();

                    switch (networkSubType) {
                        case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                            return "Mobile (Unknown)";
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            return "2G";
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            return "3G";
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return "4G";
                        case TelephonyManager.NETWORK_TYPE_NR:
                            return "5G";
                        default:
                            return "Mobile (Unknown)";
                    }
                } else {
                    return "Unknown";
                }
            } else {
                return "No Network";
            }
        } else {
            Log.e(TAG, "ConnectivityManager or TelephonyManager is null");
            return "Unknown";
        }
    }
}
